import * as _ from 'lodash';

export class TreeUtils{
    constructor() {
    }
    convertToTree(tree: any) {
        tree.forEach(item => {
            item.key = item.id;
            if (item.children != null && item.children.length !== 0) {
                this.convertToTree(item.children);
                item.isLeaf = false;
            } else {
                item.isLeaf = true;
            }
        });
    }


    /**
     * 构建树
     * @param data
     * @param parentKeyName
     * @param keyName
     */
    static buildTree(data,parentKeyName,keyName,expandAll) {
        const map = new Map();
        const tree = [];

        // 首先将所有节点放入map中
        data.forEach(item => {
            map.set(item[keyName], { ...item,expand:expandAll, children: [] });
        });

        // 然后构建树形结构
        data.forEach(item => {
            if (item[parentKeyName] === 0) {
                tree.push(map.get(item[keyName]));
            } else {
                const parent = map.get(item[parentKeyName]);
                if (parent) {
                    parent.children.push(map.get(item[keyName]));
                }else {
                    tree.push(map.get(item[keyName]));
                }
            }
        });
        this.onSetTreeLevel(tree,0)
        return tree;
    }

    /**
     * 设置菜单的level层级
     * @param array 需要转换的原始数组
     * @param level 要设置的层级
     */
    static onSetTreeLevel(array: any, level: number) {
        _.forEach(array, (item) => {
            if (!item.level) {
                item.level = level;
            }
            if (item.children) {
                if (item.children.length === 0){
                    delete item.children
                }else {
                    const _level = item.level + 1;
                    this.onSetTreeLevel(item.children, _level);
                }
            }
        });
    }

}
